package controllers

import (
	comm "com.wangzhumo.lottery/common"
	"com.wangzhumo.lottery/models"
	"com.wangzhumo.lottery/services"
	"com.wangzhumo.lottery/web/viewmodels"
	"encoding/json"
	"fmt"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	"time"
)

type AdminGiftController struct {
	Ctx            iris.Context
	ServiceUser    services.UserService
	ServiceIp      services.BlackIpService
	GiftServices   services.GiftServices
	CodeService    services.CodeService
	UserDayService services.UserDayService
	ResultService  services.ResultService
}

// Get 首页
func (c *AdminGiftController) Get() mvc.Result {
	gifts, _ := c.GiftServices.GetAll(true)
	total := len(gifts)

	// format prize data
	for i, gift := range gifts {
		// 修改数据
		prizeData := make([][2]int, 0)
		err := json.Unmarshal([]byte(gift.PrizeData), &prizeData)
		if err != nil || len(prizeData) < 1 {
			gifts[i].PrizeData = "[]"
		} else {
			planData := make([]string, len(prizeData))
			// 填充数据,对这个prizeData中的每一个元素操作
			for index, datum := range prizeData {
				fromUnixTime := comm.FormatFromUnixTime(int64(datum[0]))
				planData[index] = fmt.Sprintf("[%s]:%d", fromUnixTime, datum[1])
			}
			marshal, err := json.Marshal(planData)
			if err == nil && len(marshal) > 0 {
				gifts[i].PrizeData = string(marshal)
			} else {
				gifts[i].PrizeData = "[]"
			}
		}
	}
	return mvc.View{
		Name: "admin/gift.html",
		Data: iris.Map{
			"Title":    "礼物管理后台",
			"Channel":  "gift",
			"Datalist": gifts,
			"Total":    total,
		},
		Layout: "admin/layout.html",
	}
}

// GetEdit 修改礼物数据
func (c *AdminGiftController) GetEdit() mvc.Result {
	// 获取参数数据
	id := c.Ctx.URLParamIntDefault("id", 0)
	viewGift := viewmodels.ViewGift{}
	if id > 0 {
		// 获取数据
		ltGift, _ := c.GiftServices.Get(id,false)
		viewGift.Id = ltGift.Id
		viewGift.Title = ltGift.Title
		viewGift.PrizeNum = ltGift.PrizeNum
		viewGift.PrizeCode = ltGift.PrizeCode
		viewGift.PrizeTime = ltGift.PrizeTime
		viewGift.Img = ltGift.Img
		viewGift.Displayorder = ltGift.Displayorder
		viewGift.Gtype = ltGift.Gtype
		viewGift.Gdata = ltGift.Gdata
		viewGift.TimeBegin = comm.FormatFromUnixTime(int64(ltGift.TimeBegin))
		viewGift.TimeEnd = comm.FormatFromUnixTime(int64(ltGift.TimeEnd))
	}

	return mvc.View{
		Name: "admin/giftEdit.html",
		Data: iris.Map{
			"Title":   "礼物管理后台",
			"Channel": "gift",
			"info":    viewGift,
		},
		Layout: "admin/layout.html",
	}
}

// PostSave 修改数据
func (c *AdminGiftController) PostSave() mvc.Result {
	// 获取参数数据
	viewGift := viewmodels.ViewGift{}
	err := c.Ctx.ReadForm(&viewGift)
	if err != nil {
		fmt.Println("admin gift save error", err)
		return mvc.Response{
			Text: fmt.Sprintf("读取上传的数据错误 GetEdit ，err = %s", err),
		}
	}

	ltGift := models.LtGift{}
	ltGift.Id = viewGift.Id
	ltGift.Title = viewGift.Title
	ltGift.PrizeNum = viewGift.PrizeNum
	ltGift.PrizeCode = viewGift.PrizeCode
	ltGift.PrizeTime = viewGift.PrizeTime
	ltGift.Img = viewGift.Img
	ltGift.Displayorder = viewGift.Displayorder
	ltGift.Gtype = viewGift.Gtype
	ltGift.Gdata = viewGift.Gdata
	timeBegin, errBegin := comm.ParseTime(viewGift.TimeBegin)
	timeEnd, errEnd := comm.ParseTime(viewGift.TimeEnd)
	if errBegin != nil || errEnd != nil {
		return mvc.Response{
			Text: "开始时间/结束时间有误",
		}
	}
	ltGift.TimeBegin = int(timeBegin.Unix())
	ltGift.TimeEnd = int(timeEnd.Unix())

	// 存在则更新
	if ltGift.Id > 0 {
		dbGift, _ := c.GiftServices.Get(ltGift.Id,false)
		if dbGift != nil {
			if dbGift.PrizeNum != ltGift.PrizeNum {
				// 更新礼物的数量
				ltGift.LeftNum = dbGift.LeftNum - (dbGift.PrizeNum - ltGift.PrizeNum)
				// 如果小于0  或者是说 总数为0那么剩余数量也应该是0
				if ltGift.LeftNum < 0 || ltGift.PrizeNum <= 0 {
					ltGift.LeftNum = 0
				}
				dbGift.SysStatus = ltGift.SysStatus
				// TODO 奖品数量变换后 - 更新其他的数据（cache ...）
			}else{
				ltGift.LeftNum = dbGift.LeftNum
			}

			if dbGift.PrizeTime != ltGift.PrizeTime {
				// TODO 奖品的发奖周期变化了，需要更新其他的地方
			}


			ltGift.SysUpdated = int(time.Now().Unix())
			ltGift.SysIp = comm.ClientIp(c.Ctx.Request())
			c.GiftServices.Update(&ltGift, []string{"title", "prize_num", "left_num", "prize_code", "prize_time",
				"img", "displayorder", "gtype", "gdata", "time_begin", "time_end", "sys_updated"})
		}else{
			ltGift.Id = 0
		}
	}
	if ltGift.Id == 0 {
		// 需要写入sys相关数据，以及left
		ltGift.SysIp = comm.ClientIp(c.Ctx.Request())
		ltGift.SysCreated = int(time.Now().Unix())
		ltGift.LeftNum = viewGift.PrizeNum
		c.GiftServices.Insert(&ltGift)
	}

	return mvc.Response{
		Path: "/admin/gift",
	}
}

// GetDelete 删除礼物 - 更新为1
func (c *AdminGiftController) GetDelete() mvc.Result {
	giftId, err := c.Ctx.URLParamInt("id")

	// 获取到id，直接移除 sys_status = 1
	if err == nil {
		c.GiftServices.Delete(giftId)
	}

	return mvc.Response{
		Path: "/admin/gift",
	}
}

// GetReset 恢复礼物 - 更新为0
func (c *AdminGiftController) GetReset() mvc.Result {
	giftId, err := c.Ctx.URLParamInt("id") // 获取到id，直接移除
	if err == nil {
		c.GiftServices.Update(&models.LtGift{
			Id:        giftId,
			SysStatus: 0},
			[]string{"sys_status"},
		)
	}
	return mvc.Response{
		Path: "/admin/gift",
	}
}
